﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace GameEngine
{
    public class Player : AnimatedSprite
    {

        public float Speed
        {
            get { return speed; }
            set
            {
                speed = (float)Math.Max(value, 1f);
            }
        }
        private float speed = 1;

        Vector2 destination;

        public Player(Texture2D texture, int tile_width, int tile_height)
            : base(texture, tile_width, tile_height)
        {
            AddAnimation("Up", new Animation(4, 0, 0, 1));
            AddAnimation("Right", new Animation(4, 0, 1, 1));
            AddAnimation("Down", new Animation(4, 0, 2, 1));
            AddAnimation("Left", new Animation(4, 0, 3, 1));
            SetAnimation("Down", false);
            FramesPerSecond = 4;
        }

        public override void Update(GameTime gameTime)
        {
            if (position.X == destination.X && position.Y == destination.Y)
                Check();
            else
                Move();

            base.Update(gameTime);
        }

        public void Check()
        {
            KeyboardState keyboard = Keyboard.GetState();

            if (keyboard.IsKeyDown(Keys.W))
            {
                destination.Y -= tile_height;
                SetAnimation("Up");
            }
            else if (keyboard.IsKeyDown(Keys.A))
            {
                destination.X -= tile_width;
                SetAnimation("Left");
            }
            else if (keyboard.IsKeyDown(Keys.S))
            {
                destination.Y += tile_height;
                SetAnimation("Down");
            }
            else if (keyboard.IsKeyDown(Keys.D))
            {
                destination.X += tile_width;
                SetAnimation("Right");
            }
            else
            {
                Animating = false;
            }
        }

        public void Move()
        {
            if (position.X < destination.X)
                position.X += speed;
            if (position.X > destination.X)
                position.X -= speed;

            if (position.Y < destination.Y)
                position.Y += speed;
            if (position.Y > destination.Y)
                position.Y -= speed;
        }
    }
}
